package test.work.dao;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import test.work.vo.Department;

public class DepartmentDao implements InterfaceDao<Department> {
	private ArrayList<Department> lists;
	private final String FILE = "departmentDB.data";
	
	@Override
	public void insertItem(Department item) {
		if(!lists.contains(item)){
			lists.add(item);
		}
	}

	@Override
	public void deleteItem(Department item) {
		if(lists.contains(item)){
			lists.remove(item);
		}
	}

	@Override
	public void updateItem(Department item) {
		if(lists.contains(item)){
			lists.set(lists.indexOf(item), item);
		}
	}

	@Override
	public Department searchItem(Department item) {
		Department searchDepartment=null;
		if(lists.contains(item)){
			searchDepartment = lists.get(lists.indexOf(item)); 
		}
		return searchDepartment;
	}

	@Override
	public void prnItemList(Comparator<Department> comp) {
		if(comp!=null){
			Collections.sort(lists,comp);
		}else{
			Collections.sort(lists);
		}
		for (Department dept : lists) {
			System.out.println(dept);
		}
	}

	@Override
	public void loadFile(){
		ObjectInputStream ois = null;
		try {
			ois=new ObjectInputStream(new BufferedInputStream(new FileInputStream(FILE)));
			lists=(ArrayList<Department>) ois.readObject();			
		} catch (FileNotFoundException e) {
				try {
					new File(FILE).createNewFile();
					lists=new ArrayList<>();	
				} catch (IOException e1) {}
						
		}catch(Exception e){}
		finally{
			if(ois!=null)try {ois.close();} catch (IOException e) {}
		}
	}

	@Override
	public void saveFile(){
		ObjectOutputStream oos=null;
			try {
				oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILE)));
				oos.writeObject(lists);
			}  catch (Exception e) {}
			finally{
				if(oos!=null)try {oos.close();} catch (IOException e) {}	
			}			
	}
}
